using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace ebookreader
{
    public class TextEdit
    {
        #region Fields

        SpriteBatch sprite_batch;
        SpriteFont font;
        Texture2D background;
        Rectangle rectangle;
        Vector2 text_position, cursor_position;
        Color color;

        public string text, cursor;
        int max_char_number;

        #endregion

        #region Constructors

        public TextEdit(SpriteBatch sprite_batch, SpriteFont font, Texture2D background, Color color, Vector2 position, 
            string str, int width, int height)
        {
            this.sprite_batch = sprite_batch;
            this.background = background;
            this.font = font;
            this.text = str;
            this.color = color;

            rectangle = new Rectangle((int)position.X, (int)position.Y, width, height);

            max_char_number = 5; // Da modificare

            cursor = "_";

            var text_size = font.MeasureString(str + cursor);
            cursor_position = text_position = new Vector2(rectangle.X + rectangle.Width / 2.0f - text_size.X / 2.0f,
                rectangle.Y + rectangle.Height / 2.0f - text_size.Y / 2.0f);            
        }

        #endregion

        #region Draw

        public void DrawInsideSpriteBatch(GameTime gameTime)
        {
            sprite_batch.Draw(background, rectangle, Color.White);
            sprite_batch.DrawString(font, text, text_position, color);
            sprite_batch.DrawString(font, cursor, cursor_position, 
                color * (((float)Math.Sin(gameTime.TotalGameTime.TotalSeconds) + 1.0f) / 2.0f));
        }

        public void DrawOutsideSpriteBatch(GameTime gameTime)
        {
            sprite_batch.Begin();

            DrawInsideSpriteBatch(gameTime);

            sprite_batch.End();
        }

        #endregion

        #region Public Methods

        public void AddChar(string str)
        {
            text += str;
            RecalculateStringsPosition();
        }

        public void RemoveChar()
        {
            text = text.Substring(0, Math.Max(0, text.Length - 1));
            RecalculateStringsPosition();
        }

        #endregion

        #region Private Methods

        void RecalculateStringsPosition()
        {
            var text_size = font.MeasureString(text + cursor);
            text_position.X = rectangle.X + rectangle.Width / 2.0f - text_size.X / 2.0f;

            cursor_position.X = text_position.X + text_size.X - font.MeasureString(cursor).X;
        }

        #endregion
    }
}
